package net.forty2ware.vintagesofa

import net.sf.json.JSONObject

protected class CouchDbHelper {

  static final String MIME_TYPE = 'application/json'

  private HttpHelper httpHelper = new HttpHelper()

  protected String getServerUrl(Server server, String path) {
    if (!(path ==~ /^\/.+$/)) { path = '/' + path }
    return "http://${server.hostname}:${server.port}${server.context}${path}"
  }

  protected String getDatabaseUrl(Database database, String path) {
    if (!(path ==~ /^\/.+$/)) { path = '/' + path }
    return getServerUrl(database?.server, "${database.name}${path}")
  }

  private def processResponse(String responseString) {
    def response = new JSONObject()
    response.put('JSON', responseString)
    return JSONObject.toBean(response).JSON
  }

  private String getJsonObjectFromMap(Map content) {
    def jsonObject = new JSONObject()
    jsonObject.putAll(content)
    return jsonObject.toString()
  }

  def post(Database database, String path, Map content) {

    return processResponse(
      httpHelper.post(
        getDatabaseUrl(database, path),
        [:],
        MIME_TYPE,
        getJsonObjectFromMap(content)
      )
    )

  }

  def listDatabases(Server server) {
    return processResponse(
      httpHelper.get(getServerUrl(server, '_all_dbs'))
    )
  }

  def get(Database database, String path) {
    return processResponse(
      httpHelper.get(getDatabaseUrl(database, path))
    )
  }

  def put(Database database, String path) {
    return processResponse(
      httpHelper.put(getDatabaseUrl(database, path))
    )
  }
    
  def delete(Database database, String path) {
    return processResponse(
      httpHelper.delete(getDatabaseUrl(database, path))
    )
  }
    
}
